package com.stack.linkedlist;

public class LinkedListStack {
    private Node head;
    private Node top;

    public LinkedListStack() {
        this.head = null;
        this.top = null;
    }

    public void push(int data) {
        if (head == null) {
            head = new Node(data);
            top = head;
            return;
        }

        top.next = new Node(data);
        top.next.pre = top;
        top = top.next;
    }

    // 判断是否为空
    private boolean isEmpty() {
        return head == null;
    }

    public int pop() {
        if (isEmpty()) {
            throw new RuntimeException("栈空，无法将数据出栈");
        }

        int t = top.data;
        top = top.pre;
        top.next = null;
        // 如果栈内无数据
        if(top == null) {
            head = null;
        }

        return t;
    }

    public void show() {
        if (isEmpty()) {
            throw new RuntimeException("栈空，无法将数据出栈");
        }

        Node tmp = head;
        while (true) {
            if (tmp == null) {
                break;
            }
            System.out.printf("%d " , tmp.data);
            tmp = tmp.next;
        }
    }

    // 求栈顶元素
    public int top() {
        return this.top.data;
    }
}
